using Microsoft.OpenApi.Models;
using Microsoft.OpenApi.Any;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Net;
using System.Text.Json;

namespace JGSY.CMS.LowCode.Platform.Infrastructure.Swagger
{
    /// <summary>
    /// Swagger通用响应操作过滤器
    /// 为所有API操作添加标准化的响应类型定义
    /// </summary>
    public class SwaggerCommonResponsesOperationFilter : IOperationFilter
    {
        /// <summary>
        /// 应用操作过滤器，为API操作添加通用响应定义
        /// </summary>
        /// <param name="operation">OpenAPI操作对象</param>
        /// <param name="context">操作过滤器上下文</param>
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            // 确保responses集合存在
            operation.Responses ??= new OpenApiResponses();

            // 添加400 - 请求参数错误
            if (!operation.Responses.ContainsKey("400"))
            {
                operation.Responses.Add("400", new OpenApiResponse
                {
                    Description = "请求参数错误",
                    Content = new Dictionary<string, OpenApiMediaType>
                    {
                        ["application/json"] = new OpenApiMediaType
                        {
                            Schema = new OpenApiSchema
                            {
                                Reference = new OpenApiReference
                                {
                                    Type = ReferenceType.Schema,
                                    Id = "ApiErrorResponse"
                                }
                            },
                            Example = new OpenApiString(@"{
                                ""success"": false,
                                ""errorCode"": 4001,
                                ""message"": ""请求参数验证失败"",
                                ""details"": ""Name字段不能为空"",
                                ""timestamp"": ""2024-01-01T12:00:00Z"",
                                ""traceId"": ""12345678-1234-1234-1234-123456789012""
                            }")
                        }
                    }
                });
            }

            // 添加401 - 未授权
            if (!operation.Responses.ContainsKey("401"))
            {
                operation.Responses.Add("401", new OpenApiResponse
                {
                    Description = "未授权访问",
                    Content = new Dictionary<string, OpenApiMediaType>
                    {
                        ["application/json"] = new OpenApiMediaType
                        {
                            Schema = new OpenApiSchema
                            {
                                Reference = new OpenApiReference
                                {
                                    Type = ReferenceType.Schema,
                                    Id = "ApiErrorResponse"
                                }
                            },
                            Example = new OpenApiString(@"{
                                ""success"": false,
                                ""errorCode"": 2001,
                                ""message"": ""身份验证失败"",
                                ""details"": ""令牌无效或已过期"",
                                ""timestamp"": ""2024-01-01T12:00:00Z"",
                                ""traceId"": ""12345678-1234-1234-1234-123456789012""
                            }")
                        }
                    }
                });
            }

            // 添加403 - 权限不足
            if (!operation.Responses.ContainsKey("403"))
            {
                operation.Responses.Add("403", new OpenApiResponse
                {
                    Description = "权限不足",
                    Content = new Dictionary<string, OpenApiMediaType>
                    {
                        ["application/json"] = new OpenApiMediaType
                        {
                            Schema = new OpenApiSchema
                            {
                                Reference = new OpenApiReference
                                {
                                    Type = ReferenceType.Schema,
                                    Id = "ApiErrorResponse"
                                }
                            },
                            Example = new OpenApiString(@"{
                                ""success"": false,
                                ""errorCode"": 3001,
                                ""message"": ""权限验证失败"",
                                ""details"": ""您没有执行此操作的权限"",
                                ""timestamp"": ""2024-01-01T12:00:00Z"",
                                ""traceId"": ""12345678-1234-1234-1234-123456789012""
                            }")
                        }
                    }
                });
            }

            // 添加404 - 资源未找到 (仅对GET、PUT、DELETE操作)
            var httpMethod = context.ApiDescription.HttpMethod?.ToUpper();
            if ((httpMethod == "GET" || httpMethod == "PUT" || httpMethod == "DELETE") 
                && !operation.Responses.ContainsKey("404"))
            {
                operation.Responses.Add("404", new OpenApiResponse
                {
                    Description = "资源未找到",
                    Content = new Dictionary<string, OpenApiMediaType>
                    {
                        ["application/json"] = new OpenApiMediaType
                        {
                            Schema = new OpenApiSchema
                            {
                                Reference = new OpenApiReference
                                {
                                    Type = ReferenceType.Schema,
                                    Id = "ApiErrorResponse"
                                }
                            },
                            Example = new OpenApiString(@"{
                                ""success"": false,
                                ""errorCode"": 5001,
                                ""message"": ""请求的资源不存在"",
                                ""details"": ""指定的ID对应的资源未找到"",
                                ""timestamp"": ""2024-01-01T12:00:00Z"",
                                ""traceId"": ""12345678-1234-1234-1234-123456789012""
                            }")
                        }
                    }
                });
            }

            // 添加500 - 服务器内部错误
            if (!operation.Responses.ContainsKey("500"))
            {
                operation.Responses.Add("500", new OpenApiResponse
                {
                    Description = "服务器内部错误",
                    Content = new Dictionary<string, OpenApiMediaType>
                    {
                        ["application/json"] = new OpenApiMediaType
                        {
                            Schema = new OpenApiSchema
                            {
                                Reference = new OpenApiReference
                                {
                                    Type = ReferenceType.Schema,
                                    Id = "ApiErrorResponse"
                                }
                            },
                            Example = new OpenApiString(@"{
                                ""success"": false,
                                ""errorCode"": 9001,
                                ""message"": ""系统内部错误"",
                                ""details"": ""服务器处理请求时发生未知错误"",
                                ""timestamp"": ""2024-01-01T12:00:00Z"",
                                ""traceId"": ""12345678-1234-1234-1234-123456789012""
                            }")
                        }
                    }
                });
            }

            // 为POST操作添加409 - 资源冲突
            if (httpMethod == "POST" && !operation.Responses.ContainsKey("409"))
            {
                operation.Responses.Add("409", new OpenApiResponse
                {
                    Description = "资源冲突",
                    Content = new Dictionary<string, OpenApiMediaType>
                    {
                        ["application/json"] = new OpenApiMediaType
                        {
                            Schema = new OpenApiSchema
                            {
                                Reference = new OpenApiReference
                                {
                                    Type = ReferenceType.Schema,
                                    Id = "ApiErrorResponse"
                                }
                            },
                            Example = new OpenApiString(@"{
                                ""success"": false,
                                ""errorCode"": 5002,
                                ""message"": ""资源已存在"",
                                ""details"": ""具有相同标识的资源已经存在"",
                                ""timestamp"": ""2024-01-01T12:00:00Z"",
                                ""traceId"": ""12345678-1234-1234-1234-123456789012""
                            }")
                        }
                    }
                });
            }
        }
    }
}
